<template>
  <div>
    <!-- 返回按钮 -->
   <div class="top" @click="home">
      <van-nav-bar
      left-text="返回"
      left-arrow
      ></van-nav-bar>
    </div>

    <!-- 店铺名称 -->
    <div class="center">
      <van-cell-group>
        <van-cell >
          <template #title>
            <span class="span5">{{shop.shopName}}</span>
          </template>
          <template #icon>
            <van-icon :name="getShopImgPath(shop.shopImg)" 
            size="80"
            class="search-icon" />
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 商品分类 -->
    <van-tabs v-model="active" animated>
      <van-tab title="点菜">
        <div class="container content">
          <div class="sidebar">

            <van-sidebar v-model="activeKey" @change="onChange">
              <van-sidebar-item
                :title="item.itemTypeName"
                :name="item.itemTypeId"
                v-for="(item, index) in sidebarList"
                :key="index"
                @click="queryItems(item.itemTypeId)"
              ></van-sidebar-item>
            </van-sidebar>
          </div>

        <!-- 商品 -->
        <div class="content" ref="content">
          <van-card
            desc="描述信息"
            :title="item.itemName"
            :thumb="getImagePath(item.itemPicture)"
            v-for="(item, index) in itemList"
            :key="index"
          >
          <template #price>
              <span class="span3">￥{{item.itemPrice}}</span>
            </template>
            <template #tags>
              <van-tag plain type="danger">标签</van-tag>
              <van-tag plain type="danger">标签</van-tag>
            </template>

            <template #footer>
              <van-button class="button-with-badge" size="mini" @click="onShow(item)">
                      选规格
              </van-button>
            </template>
          </van-card>
        </div>

        </div>
      </van-tab>

      <van-tab title="套餐">
        套餐界面
      </van-tab>

      <van-tab title="评价">
        评价界面
      </van-tab>
      
    </van-tabs>
    <!-- 选规格窗口 -->
    <div>
      <van-dialog width="400px" v-model="show" @confirm="onConfirm" @cancel="onCancel" show-cancel-button confirmButtonText="加入购物车" confirmButtonColor="#ffdd01">
          
          <div class="parent" style="height: 400px;width: 90%;margin: 0 auto; padding-top: 15px;">
            <p style="font-size: 20px;">{{ item.itemName }}</p>
            <div style="height: 300px;">
              <div v-for="option in itemObj" :key="option.id" style="padding-bottom: 15px;">
                <p >{{ option.weightName }}</p>
                <!-- 单选框 -->
                <van-radio-group v-model="option.selectedValue" direction="horizontal" checked-color="#FFCF5D">
                  <van-radio v-for="value in option.values" :key="value" :name="value">
                    {{ value }}
                  </van-radio>
                </van-radio-group>
              </div>
            </div>

             <!-- 底部描述 -->
             <div class="child">
              <div><span style="font-size: 13px;">已选规格：</span>
                <span v-for="(item, index) in itemObj" :key="index" style="font-size: 13px;">{{item.selectedValue}}&nbsp;&nbsp;&nbsp;</span>
              </div>
              <div style="display: flex;justify-content: right;">
                <span style="font-size: 16px;">总计：</span>
                <span style="color: red;font-size: 16px;"></span>
                <span style="color: red;font-size: 20px;">￥{{ item.itemPrice }}</span>
              </div>
            </div>

          </div>
      </van-dialog>
    </div>

    <!-- 底部购物车 -->
    <van-goods-action>
      <van-goods-action-icon icon="cart-o" text="购物车" :badge="itemNumber" v-if="itemNumber != 0" @click="showWindow"></van-goods-action-icon>
      <van-goods-action-icon icon="cart-o" text="购物车" v-if="itemNumber == 0" @click="showWindow"></van-goods-action-icon>
      <span class="span4">
        ￥{{ total }}
      </span>
      <van-goods-action-button type="danger" text="结算"
       @click="isLogin"
       
       style="font-weight: 
       bolder;color: black;" 
       color="#ffdd01">
      </van-goods-action-button>
    </van-goods-action>

    <!-- 购物车弹出 -->
    <van-action-sheet v-model="gowushow" title="购物车">
          <div style="height: 300px;">
            <!-- 购物商品-->
            <van-card
              v-for="s in shoppingCart"
              :key="s.shoppingId"
              :num="s.itemNum"
              :price="s.itemPrice" 
              :thumb="getImagePath(s.itemPicture)"
            >
              <template #title>
                <span class="span1">{{s.itemName}}</span><br>
              </template>
              <template #desc>
                <div>
                  <span  v-for="a in s.shoppingCartDetails"
                      :key="a.id"  
                      class="span2">
                      {{a.selectedValue}}、
                  </span>
                </div>
              </template>
              <template #price>
                <span class="span3">￥{{s.itemPrice}}</span><br>
              </template>
              <template #footer>
                <van-button size="small" @click="updateShopPingItemNum1(s)">-</van-button>
                <van-button size="small" @click="updateShopPingItemNum2(s)">+</van-button>
              </template>
            </van-card>
          </div>
    </van-action-sheet>
</div>
</template>

<script>
import { Toast } from 'vant';
import axios from 'axios';
import qs from 'qs'
export default {
  name: 'Shop',
  props:['id'],
  data() {
    return {
      baseUrl: 'http://localhost:8081/images/item/',
      shopImg:"http://localhost:8081/images/shop/",
      // 商品多选值
      checkBoxResult:[],
      radio:0,
      activeKey: 0,
      badgeContent: 0,
      checked: true,
      sidebarList: [],
      isScrolling: false,
      active:0,
      // 选规格。
      show:false,
      // 商品列表
      itemList:[],
      // 商品对象
      itemObj:[],
      // 规格商品对象
      item:{},
      // 商品的数量
      itemNumber:0,
      // 是否打开购物车
      gowushow: false,
      // 商家对象
      shop:{},
      // token密钥
      token:'Bearer ' + localStorage.getItem("token"),
      // 购物车
      shoppingCart:[],
      // 加载购物车
      isShoppingCart:false,
      user:{}
}
  },
  computed:{
    total(){
      let total = 0;
      if (this.isShoppingCart) {
        this.shoppingCart.forEach(item => {
          total += (item.itemPrice * item.itemNum)
        });
      }
      return total.toFixed(2);
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.setupScrollEvent();
      this.setupTouchEvents();
  });
  },
  methods: {
    //拼接地址
    getImagePath(imgName){
            return `${this.baseUrl}${imgName}`;
        },
    //商家图片地址
    getShopImgPath(imgName){
        return `${this.shopImg}${imgName}`
    },
    isLogin(){
      if (this.$store.state.isLogin) {
        this.$router.push({path:`/submitOrder/${this.id}`})
      } else {
        Toast("请登录!")
      }
    },
    // 减
    updateShopPingItemNum1(shopPing){
      console.log(shopPing);
      if (shopPing.itemNum === 1) {
        axios.post('http://localhost:9090/api/ShopPing/delete',{
            id:shopPing.shoppingId,
          })        
          .then(res => {    
            if (res.data.code === 200) {
              this.shoppingCart = this.shoppingCart.filter(obj => JSON.stringify(obj) !== JSON.stringify(shopPing));
              this.itemNumber--
            }
            console.log(res.data);
          })        
          .catch(err => {            
              console.log(err.data)        
          }) 
        return;
      }
      axios.post('http://localhost:9090/api/ShopPing/update/itemNum',{
          id:shopPing.shoppingId,
          itemNum:shopPing.itemNum - 1
        })        
        .then(res => {   
          if (res.data.code === 200) {
            shopPing.itemNum = shopPing.itemNum - 1
            this.itemNumber--
          } 
          console.log(res.data);
        })        
        .catch(err => {            
            console.log(err.data)        
        }) 
    },
    // 加
    updateShopPingItemNum2(shopPing){
      axios.post('http://localhost:9090/api/ShopPing/update/itemNum',{
          id:shopPing.shoppingId,
          itemNum:shopPing.itemNum + 1
        })        
        .then(res => {    
          if (res.data.code === 200) {
            shopPing.itemNum = shopPing.itemNum + 1
            this.itemNumber++
          }
          console.log(res.data);
        })        
        .catch(err => {            
            console.log(err.data)        
        }) 
    },
    queryShopPing(){
      console.log("id:" + this.$store.state.uid);
      let that = this
      //1.发起axios请求添加至购物车
      axios.defaults.headers['Authorization'] = that.token;
      if (this.$store.state.isLogin) {
        axios.get('http://localhost:9090/api/user/ShopPing/query', {
        params:{
            uId:this.$store.state.uid,
            shopId:this.id,
          }
        })
      .then(response => {
        // 处理响应数据
        this.shoppingCart = response.data.data;
        this.itemNumber = 0
        this.shoppingCart.forEach(item => {
          this.itemNumber += item.itemNum
          item.shoppingCartDetails = JSON.parse(item.shoppingCartDetails);
          console.log(item.itemPrice + item.itemPrice);
        });
        this.isShoppingCart = true
        console.log(this.shoppingCart);
      })
      .catch(error => {
        // 处理错误
        console.error(error);
      });
      }
    },
    queryShop(){
      axios.get("http://localhost:9090/api/shop/getListShopAndItemAndItemType",{
        params:{
          shopId:this.id,
        }
      })        
        .then(res => {    
          console.log(res.data.data);
          this.shop = res.data.data.shop;
          this.sidebarList = res.data.data.itemTypeList
          this.queryItems(res.data.data.itemTypeList[0].itemTypeId)
        })        
        .catch(err => {            
            console.log(err.data)        
        }) 
    },
    
    queryItems(id){
      axios.get("http://localhost:9090/api/item/getItemListItemType",{
        params:{
          itemTypeId:id,
        }
      })        
        .then(res => {    
          console.log(res.data.data);
          this.itemList = res.data.data;
        })        
        .catch(err => {            
            console.log(err.data)        
        }) 
      console.log("TypeId:"+id);
    },
    home(){
      this.$router.push({path:"/"})
    },

    showWindow(){
      this.gowushow = true
    },
    //点击加入购物车
    onConfirm(){
      let that = this

      //1.发起axios请求添加至购物车
      const postData = {
        uid: this.$store.state.uid,
        itemId: this.item.itemId,
        shopId: this.item.shopId,
        itemNum: 1,
        shoppingCartDetails: JSON.stringify(this.itemObj)
      };
      const encodedData = qs.stringify(postData);

      axios.post('http://localhost:9090/api/user/ShopPing/add', encodedData, {
        headers: {
          'Authorization': that.token,
          'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
        }
      })
      .then(response => {
        // 处理响应数据
        console.log(response.data);
        if (response.data.code === 200) {
          this.queryShopPing()
          // this.itemNumber += 1;
        } else {
          this.$toast('请登录!');
          this.$store.state.isLogin = false;
        }
      })
      .catch(error => {
        // 处理错误
        console.error(error);
      });
      
      //2.接收当前用户的购物车数量
      //例：
      // this.itemNumber += 1
      // this.badgeContent = 1
    },
    //点击取消
    onCancel(){
      // console.log(2222);
      this.itemObj = {}
      // console.log(this.itemObj);
    },
    //点击选规格
    onShow(item){
      this.show = true
      this.item = item;
      this.itemObj = JSON.parse(item.itemDetails);
      console.log(this.item);

    },
    // 判断有没有tokn并检查是否登录
    isTokn(){
            let token = localStorage.getItem("token") ;
            
            if(token != null) {
                this.showUserInfo();
            } else {
                this.$store.state.isLogin = false
            }
        },
        showUserInfo(){
            let that = this
            console.log(this);
            const instance = axios.create({
                baseURL: 'https://api.example.com',
                timeout: 5000,
                headers: {
                    // 设置请求头，把 token 传递给服务器程序，以便于认证
                    'Authorization': that.token
                }
            });
            // 发起请求
            instance.get('http://localhost:9090/api/user')
            .then(response => {
                // 处理响应数据
                console.log(response.data);
                if (response.data.code === 200) {
                    this.$store.state.isLogin = true
                    this.user = response.data.data;
                    this.$store.state.uid = response.data.data.uid;
                } else{
                    this.$store.state.isLogin = false
                }
            })
            .catch(error => {
                // 处理错误
                console.error(error);
            });
        },
    //点击分类
    onChange(index) {
      console.log(index);
      console.log('activeKey=' + this.activeKey);
    },

    //以下是固定滚轮
    handleScroll(event) {
      if (!this.isScrolling) {
        event.preventDefault();
        const deltaY = event.deltaY;
        const content = this.$refs.content;
        content.scrollTop += deltaY;
      }
    },
    handleTouchStart(event) {
      this.startY = event.touches[0].clientY;
    },
    handleTouchMove(event) {
      const content = this.$refs.content;
      const deltaY = event.touches[0].clientY - this.startY;
      content.scrollTop -= deltaY;
      this.startY = event.touches[0].clientY;
    },
    setupScrollEvent() {
      const content = this.$refs.content;
      content.addEventListener('wheel', this.handleScroll, { passive: false });
    },
    setupTouchEvents() {
      const content = this.$refs.content;
      content.addEventListener('touchstart', this.handleTouchStart);
      content.addEventListener('touchmove', this.handleTouchMove, {
        passive: false,
      });
    },
  },
  created(){
    this.queryShop();
    this.queryShopPing(); 
    this.isTokn();
   }
};
</script>

<style scoped>

/* 选规格界面样式 */
.parent{
  position: relative; /* 设置为相对定位，以便子元素可以相对于它定位 */
}
.child {
  position: absolute; /* 设置为绝对定位，相对于父容器定位 */
  bottom: 0; /* 底部距离为0，将子元素固定到底部 */
  width: 100%; /* 子容器宽度充满父容器 */
  background-color: #FAFAFA;
 }
/* 选规格界面结束 */
.button-with-badge {
  position: relative;
  background-color: #ffdd4d;
}
 
.span1{
    font-size: 15px;
}
.span2{
    font-size: 10px;
}
.span3{
  font-size: 18px;
  color: #ff3c01;
}
.span4{
  font-size: 18px;
  color: #ff9901;
}
.span5{
  font-size: 20px;
}
.button-with-badge {
  position: relative;
  background-color: #ffdd4d;
}

.badge {
  position: absolute;
  top: -11px;
  right: -12px; 
}
.container {
  display: flex;
}

.sidebar {
  /* flex: 0 0 120px; */
  overflow-y: auto;
}

.content {
  flex: 1;
  overflow-y: auto;
  height: calc(80vh - 70px);
}

.van-sidebar-item {
  background-color: #f8f8f8;
  cursor: pointer;  
}
</style>
